# How to do query validation

:::info Prerequisites

This guide assumes familiarity with the following:

- [Question answering over SQL data](/docs/tutorials/sql_qa)

:::

Perhaps the most error-prone part of any SQL chain or agent is writing valid and safe SQL queries.
In this guide we'll go over some strategies for validating our queries and handling invalid queries.

## Setup

First, get required packages and set environment variables:

import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx";

<IntegrationInstallTooltip></IntegrationInstallTooltip>

```bash
npm install @langchain/community @langchain/openai typeorm sqlite3
```

```bash
export OPENAI_API_KEY="your api key"
# Uncomment the below to use LangSmith. Not required.
# export LANGSMITH_API_KEY="your api key"
# export LANGSMITH_TRACING=true

# Reduce tracing latency if you are not in a serverless environment
# export LANGCHAIN_CALLBACKS_BACKGROUND=true
```

The below example will use a SQLite connection with Chinook database. Follow these [installation steps](https://database.guide/2-sample-databases-sqlite/) to create `Chinook.db` in the same directory as this notebook:

- Save [this](https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sql) file as `Chinook_Sqlite.sql`
- Run sqlite3 `Chinook.db`
- Run `.read Chinook_Sqlite.sql`
- Test `SELECT * FROM Artist LIMIT 10;`

Now, `Chinhook.db` is in our directory and we can interface with it using the Typeorm-driven `SqlDatabase` class:

import CodeBlock from "@theme/CodeBlock";
import DbCheck from "@examples/use_cases/sql/db_check.ts";

<CodeBlock language="typescript">{DbCheck}</CodeBlock>

## Query checker

Perhaps the simplest strategy is to ask the model itself to check the original query for common mistakes.
Suppose we have the following SQL query chain:

import FullExample from "@examples/use_cases/sql/query_checking.ts";

<CodeBlock language="typescript">{FullExample}</CodeBlock>

## Next steps

You've now learned about some strategies to validate generated SQL queries.

Next, check out some of the other guides in this section, like [how to query over large databases](/docs/how_to/sql_large_db).
